package com.usian.app.geteway.filter;

import com.usian.common.dtos.Payload;
import com.usian.common.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *  认证过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 认证业务
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、判断请求是否需要认证（登录请求不需要认证）
        // 获取请求路径，如果是登录请求，直接放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if(path.contains("/login")){
            //登录请求，直接放行
           return chain.filter(exchange);
        }

        //2、获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //2.1 判断token是否存在
        if(StringUtils.isBlank(token)){
            //token不存在，拦截请求，提示权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //2.2 如果token存在，解析token
            //3、校验token有效
            Payload payload = JwtUtils.getInfoFromToken(token);
            //4、解析token,获取用户id，存入请求头中
            Integer userId = payload.getUserId();
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId",String.valueOf(userId));
            }).build();

            //5、分发微服务
            exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //token无效
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
            return 0;
    }
}
